<template>
    <div>

    </div>
</template>

<script>
import { shareDynamic, getUserShareInfo, updateShareTemp  } from '@/request/art'
import { getUserAdverts } from '@/request/ad'
export default {
    data() {
        return{
            dynamicId: '',
            // detail: {},

            shareKey: '', //分享key
            fromUserId: '', //shareKey对应的UserId
            tempShareKey: (new Date().getTime().toString(32)) + (Math.random().toString(32).slice(2)), //前端生成的分享id,要传给后台的
            // advertInfo: {},
            // shareCardInfo: {}

        }
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        advertInfo: {
            type: Object,
            default: () => ({})
        },
    },
    computed: {

    }, 
    mounted() {

    },
    methods: {
        init(options = {}) {
            this.dynamicId = options.dynamicId
            this.shareKey = options.shareKey
            this.alertUserInfoTip()
            return new Promise(async (resolve, reject) => {
                if(options.isPoster) {
                    if(this.mixinLoginStatus) {
                        // 沒登錄沒必要更新瀏覽狀態
                        await updateShareTemp({ frontKey: this.shareKey })
                    }
                }
                let advertInfo = {}, shareCardInfo = {};
                if(this.shareKey) {
                    let res = await this.getShareInfo()
                    advertInfo = res.advertInfo
                    shareCardInfo = res.shareCardInfo
                } else {
                    advertInfo = await this.getDefaultAd()
                }
                this.wxConfig()
                resolve({
                    shareCardInfo,
                    advertInfo
                })
            })
        },

        alertUserInfoTip() {
            if(!this.shareKey && this.mixinLoginStatus) {
                if(!this.$store.state.user.userInfo.userPhone) {
                    if(new Date().format('yyyy-MM-dd') != uni.getStorageSync('editUserInfoTip')) {
                        uni.setStorageSync('editUserInfoTip', new Date().format('yyyy-MM-dd'))
                        this.$interact.modal({
                            title: '提示',
                            content: '您的名片信息不完善，去完善我的联系方式吧',
                            showCancel: true
                        }).then(action =>{
                            if(action.confirm) {
                                this.$navigate.to('/pages/user/editBusinessCard')
                            }
                        })
                    }
                }
                // if(!this.$store.state.user.userInfo.wxacodeUrl) {
                //     this.$interact.modal({
                //         title: '提示',
                //         content: '您的名片信息不完善，去完善我的微信吧',
                //         showCancel: true
                //     }).then(action =>{
                //         if(action.confirm) {
                //             this.$navigate.to('/pages/user/editBusinessCard')
                //         }
                //     })
                // }
            }

        },
        
        getShareInfo() {
            return new Promise((resolve, reject) => {
                getUserShareInfo({
                    frontKey: this.shareKey
                }).then(res => {
                    this.fromUserId = res.data.fromUserId
                    uni.setStorageSync( 'shareUserId', res.data.fromUserId)
                    let advertInfo = {}
                    if(res.data.hasOwnProperty('advert')) {
                        advertInfo = res.data.advert || {}
                    }
                    let shareCardInfo = {}
                    if(res.data.hasOwnProperty('headImg')) {
                        shareCardInfo = res.data
                    } 
                    resolve({
                        advertInfo,
                        shareCardInfo
                    })
                })
            })
        },
        getDefaultAd() {
            // 获取默认
            return new Promise((resolve, reject) => {
                getUserAdverts({
                    defalutFlag: '01',
                    pageIndex: 1,
                    pageSize: 1
                }).then(res => {
                    let advertInfo = res.data.list[0]
                    if(this.$store.state.user.userInfo.vip == '01') {
                        resolve(advertInfo)
                    } else {
                        resolve({})
                    }
                })
            })
        },
        getShareLink() {
            let linkQueryStr = this.$qs.stringify({                    
                id: this.dynamicId,
                shareKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? this.shareKey : this.tempShareKey,
                inviteUserId: this.mixinLoginStatus ? this.$store.state.user.userInfo.userId : ''
            })
            let link = location.origin +  location.pathname + '?' + linkQueryStr
            return link
        },
        wxConfig() {
            let that = this
            const formatShareData = () => {
                let desc = this.detail.context.replace(/<.*?>/ig, '') || ''
				desc = desc.replace(/(\&[a-zA-Z]*\;)/ig, '')

                desc = desc && desc.slice(0, 300) || ''
                let shareData = {
                    title: this.detail.title, // 分享标题
                    desc, // 分享描述
                    // 有shareKey的情况是非编辑状态，直接转发别人的shareKey,编辑状态会有一条自己的shareKey
                    link: this.getShareLink(), // 分享链接
                    imgUrl: this.detail.pictureUrl, // 分享图标
                } 
                console.log( JSON.parse(JSON.stringify(shareData)) );
                // jWeixin.updateAppMessageShareData({ 
                //     ...shareData,
                //     success: function () {
                //     // 设置成功
                //     }
                // })
                // jWeixin.updateTimelineShareData({ 
                //     ...shareData,
                //     success: function () {
                //     // 设置成功
                //     }
                // })

                jWeixin.onMenuShareTimeline({
                    ...shareData,
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        that.shareArt('01')
                    }
                })
                jWeixin.onMenuShareAppMessage({
                    ...shareData,
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        that.shareArt('00')
                    }
                })
            }
            if(this.mixinIsDevRunTime) {
                formatShareData()
            }
            this.$wxConfig().then(formatShareData)
        },
        shareArt(shareType) {
            if(!this.mixinLoginStatus) return;
            let data = {
                frontKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? this.shareKey : this.tempShareKey,
                fromKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? void 0 : this.shareKey || void 0,
                dynamicId: this.dynamicId,
                advertId: this.advertInfo.id || void 0
            }
            if(shareType == 'poster') {
                data.tempFlag = '01'
                data.shareType = '00'
            } else {
                data.shareType = shareType //00群聊，01朋友圈
            }
            shareDynamic(data).then(res => {
                if(process.env.NODE_ENV == 'development') {
                    this.$interact.toast('分享成功')
                } else {
                    if(shareType != 'poster') {
                        this.$interact.toast('分享成功')
                    }
                }
            })
        },


    }

}
</script>

<style>

</style>